<?php

/**
 * @author chenshubo
 * 订单申报回调通知
 */
namespace App\Service\OrderService\OrderInterfaceService;

use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\CommodityModel\SupplierCompany;
use App\Model\PssModel\Business;
use App\Service\VendorClient\OrderDeclareServiceApi\OrderDeclareServiceApiClient;
use App\Service\AppService\PushOrderSettleMentService;

class OrderDeclare extends BaseService
{ 
    /**
     * 新版本支付接口
     * @param array $param
     */
    public function orderDeclareNotify( $param = [] )
    {
        if( empty($param['requestData']) ) {
            return Normal::returnCode(Normal::FAIL,"requestData参数不能为空");
        }
        
        $message = $param['requestData'];
        //判断申报订单号
        if( empty($message['data']) ) {
            return Normal::returnCode(Normal::FAIL,"data参数缺失");
        }

        $message = current($message['data']);
        //判断申报订单号
        if( empty($message['orderNo']) ) {
            return Normal::returnCode(Normal::FAIL,"orderNo 参数缺失");
        }
        
        $supplier_dsn = $message['orderNo'];
        $orderSupplier = OrderSupplier::instance()->info(['supplier_dsn' => $supplier_dsn]);
        if( empty($orderSupplier) ) {
            return Normal::returnCode(Normal::FAIL,"未找到对应订单信息");
        }
        
        //判断是否已申报成功
        if( $orderSupplier['order_decalre_status'] == 1 ) {
            return Normal::returnCode(Normal::SUC,"当前订单已申报成功");
        }
        
        //如果发生售后，直接通知上游发生售后，不进行售后
        if( $orderSupplier['after_sale_status'] == 1 ) {
            return Normal::returnCode(Normal::SUC,"当前订单已经发生售后，不需要进行申报业务");
        }
        
        //非申报成功状态
        if( !in_array($message['returnStatus'],['2','3','120']) ) {
            $orderDeclare = [
                'order_decalre_status'  => 2,
                'order_decalre_result'  => $message['returnInfo'],
            ];
            $this->orderDecalreNotify([
                'orderDeclare'  => $orderDeclare,
                'supplierOrder' => $orderSupplier
            ]);
            return Normal::returnCode(Normal::SUC,"接收处理成功");
        }
        //获取响应支付订单信息
        $res = OrderDeclare::instance()->getSupplierOrderLists($orderSupplier);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $orderInfo      = $res['data']['orderInfo'];
        $orderGoods     = $res['data']['orderGoods'];
        $supplierInfo   = $res['data']['suppplierInfo'];
        $binfo          = $res['data']['binfo'];
        
        //如果下游做了支付单申报
        if( $orderInfo['is_pay_declare'] == 1 ) {
            $apply_extends = @json_decode($orderInfo['apply_extends'],true);
            $payConfig = [
                'payCommanyName'    => $apply_extends['payCommanyName'],
                'payCommanyCode'    => $apply_extends['payCommanyCode'],
                'enterpriseNum'     => $apply_extends['enterpriseNum'],
                'enterpriseName'    => $apply_extends['enterpriseName'],
                'paySerial'         => $apply_extends['paySerial']
            ];
        } else {//未做支付单申报就用摩宝进行刷单
            $mobaoConfig    = config('api.mobao.acount');
            $payConfig = [
                'payCommanyName'    => $mobaoConfig['PayCompanyName'],
                'payCommanyCode'    => $mobaoConfig['PayCompanyCode'],
                'enterpriseNum'     => $mobaoConfig['EBPCompanyCode'],
                'enterpriseName'    => $mobaoConfig['ebpName'],
                'paySerial'         => $orderInfo['pay_sn']
            ];
        }
        
        OrderSupplier::instance()->startTrans();
        //订单申报成功
        $orderDeclare = [
            'order_decalre_status'  => 1,
            'order_decalre_result'  => $message['returnInfo'],
        ];
        
        //修改订单申报成功状态
        $this->orderDecalreNotify([
            'orderDeclare'  => $orderDeclare,
            'supplierOrder' => $orderSupplier
        ]);
        
        //订单申报完成之后，推送给供应商
        $param = [
            'supplierOrder' => $orderInfo,
            'orderItem'     => $orderGoods,
            'companyInfo'   => $supplierInfo,
            'order'         => $payConfig,
            'binfo'         => $binfo,
            'mode'          => PushOrderSettleMentService::SETTLEMENT_MODE_PAY
        ];
        $res = OrderPushSupplier::instance()->pushSupplierOrder($param);
        //供应商推送成功，写入结算数据
        if( $res['code'] == Normal::SUC ) {
            if ( $orderInfo['is_channel_settlement'] == 1 || $orderInfo['is_supplier_settlement'] ==1 ){
                PushOrderSettleMentService::instance()->addOrderSettleMentLog($param);
            }
        }
        
        OrderSupplier::instance()->commit();
        return Normal::returnCode(Normal::SUC,$res['msg']);
    }
    
    /**
     * 获取供应商列表
     * @param array $param
     */
    public function getSupplierOrderLists( $param = [] )
    {        
        //获取订单商品
        $order_id = $param['id'];
        $bid      = $param['bid'];
        $company_id = $param['company_id'];
        $orderGoods = OrderSupplierGoods::instance()
        ->select(OrderSupplierGoods::instance()->goods_fields)
        ->where('bid',$bid)
        ->where('order_id',$order_id)
        ->get()
        ->toArray();
        if( empty($orderGoods) ) {
            return Normal::returnCode(Normal::FAIL,"获取订单数据失败");
        }
        
        //获取供应商清单信息
        $SupplierCompanyLists = SupplierCompany::instance()->getSupplierListByIds([$company_id]);
        if( empty($SupplierCompanyLists) ) {
            return Normal::returnCode(Normal::FAIL,"获取供应商信息失败");
        }
        
        return Normal::returnCode(Normal::SUC,"订单数据获取成功",[
            'orderInfo'     => $param,
            'orderGoods'    => $orderGoods,
            'suppplierInfo' => current($SupplierCompanyLists),
            'binfo'         => Business::instance()->getUserInfoByBid($param['bid'])
        ]);
    }
    
    /**
     * 订单申报推送服务
     * @param array $param
     */
    public function orderPush( $param = [] )
    {
        $param['orderDeclare'] = [
            'order_decalre_status'  => 2,
            'order_decalre_result'  => '订单预处理成功',
        ];
        $res = $this->orderDecalreNotify($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        $res = OrderDeclareServiceApiClient::instance()->OrderApply($param);
        if( $res['code'] != Normal::SUC ) {
            $param['orderDeclare'] = [
                'order_decalre_status'  => 3,
                'order_decalre_result'  => $res['msg'],
            ];
            $res = $this->orderDecalreNotify($param);
            return $res;
        }
        return Normal::returnCode(Normal::SUC,"订单申报推送成功");
    }
    
    /**
     * 订单申报状态修改
     * @param array $param
     */
    public function orderDecalreNotify( $param = [] )
    {
        $orderInfo      = $param['supplierOrder'];
        $orderDeclare   = $param['orderDeclare'];
        $time           = time();
        $where = [['id','=',$orderInfo['id']]];
        $data = [
            'order_decalre_status'  => $orderDeclare['order_decalre_status'],
            'order_decalre_result'  => $orderDeclare['order_decalre_result'],
            'order_decalre_time'    => $time,
        ];
    
        $res = OrderSupplier::instance()->edit($where,$data);
        if( !$res ) {
            return Normal::returnCode(Normal::FAIL,"订单申报修改失败");
        }
    
        return Normal::returnCode(Normal::SUC,"订单申报修改成功");
    }
}